/**
 * 项目管理 API 客户端
 * 用于与后端 API 服务通信
 */

const API_BASE_URL = '/api';

class ProjectAPI {
    /**
     * 获取所有项目
     */
    async getAllProjects() {
        try {
            const response = await fetch(`${API_BASE_URL}/projects`);
            const result = await response.json();
            
            if (!result.success) {
                throw new Error(result.error || '获取项目列表失败');
            }
            
            return result.data;
        } catch (error) {
            console.error('❌ 获取项目列表失败:', error);
            throw error;
        }
    }

    /**
     * 获取单个项目详情
     */
    async getProject(projectId) {
        try {
            const response = await fetch(`${API_BASE_URL}/projects/${projectId}`);
            const result = await response.json();
            
            if (!result.success) {
                throw new Error(result.error || '获取项目详情失败');
            }
            
            return result.data;
        } catch (error) {
            console.error('❌ 获取项目详情失败:', error);
            throw error;
        }
    }

    /**
     * 创建新项目
     */
    async createProject(name, description = '') {
        try {
            const response = await fetch(`${API_BASE_URL}/projects`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ name, description })
            });
            
            const result = await response.json();
            
            if (!result.success) {
                throw new Error(result.error || '创建项目失败');
            }
            
            return result.data;
        } catch (error) {
            console.error('❌ 创建项目失败:', error);
            throw error;
        }
    }

    /**
     * 更新项目
     */
    async updateProject(projectId, updates) {
        try {
            const response = await fetch(`${API_BASE_URL}/projects/${projectId}`, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(updates)
            });
            
            const result = await response.json();
            
            if (!result.success) {
                throw new Error(result.error || '更新项目失败');
            }
            
            return result.data;
        } catch (error) {
            console.error('❌ 更新项目失败:', error);
            throw error;
        }
    }

    /**
     * 删除项目
     */
    async deleteProject(projectId) {
        try {
            const response = await fetch(`${API_BASE_URL}/projects/${projectId}`, {
                method: 'DELETE'
            });
            
            const result = await response.json();
            
            // 检查HTTP状态码和响应结果
            if (!response.ok || !result.success) {
                throw new Error(result.error || '删除项目失败');
            }
            
            return true;
        } catch (error) {
            console.error('❌ 删除项目失败:', error);
            throw error;
        }
    }

    /**
     * 设置默认项目
     */
    async setDefaultProject(projectId) {
        try {
            const response = await fetch(`${API_BASE_URL}/projects/${projectId}/set-default`, {
                method: 'POST'
            });
            
            const result = await response.json();
            
            if (!result.success) {
                throw new Error(result.error || '设置默认项目失败');
            }
            
            return true;
        } catch (error) {
            console.error('❌ 设置默认项目失败:', error);
            throw error;
        }
    }

    /**
     * 检查 API 服务是否可用
     */
    async checkConnection() {
        try {
            const response = await fetch(`${API_BASE_URL}/projects`, {
                method: 'HEAD',
                signal: AbortSignal.timeout(3000) // 3秒超时
            });
            return response.ok;
        } catch (error) {
            return false;
        }
    }

    // ==================== 场景管理 ====================

    /**
     * 向项目添加场景
     */
    async addScene(projectId, sceneData) {
        try {
            const response = await fetch(`${API_BASE_URL}/projects/${projectId}/scenes`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(sceneData)
            });
            
            const result = await response.json();
            
            if (!result.success) {
                throw new Error(result.error || '添加场景失败');
            }
            
            return result.data;
        } catch (error) {
            console.error('❌ 添加场景失败:', error);
            throw error;
        }
    }

    /**
     * 更新场景信息
     */
    async updateScene(projectId, sceneId, updates) {
        try {
            const response = await fetch(`${API_BASE_URL}/projects/${projectId}/scenes/${sceneId}`, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(updates)
            });
            
            const result = await response.json();
            
            if (!result.success) {
                throw new Error(result.error || '更新场景失败');
            }
            
            return result.data;
        } catch (error) {
            console.error('❌ 更新场景失败:', error);
            throw error;
        }
    }

    /**
     * 删除场景
     */
    async deleteScene(projectId, sceneId) {
        try {
            const response = await fetch(`${API_BASE_URL}/projects/${projectId}/scenes/${sceneId}`, {
                method: 'DELETE'
            });
            
            const result = await response.json();
            
            if (!result.success) {
                throw new Error(result.error || '删除场景失败');
            }
            
            return true;
        } catch (error) {
            console.error('❌ 删除场景失败:', error);
            throw error;
        }
    }

    /**
     * 设置默认场景
     */
    async setDefaultScene(projectId, sceneId) {
        try {
            const response = await fetch(`${API_BASE_URL}/projects/${projectId}/scenes/${sceneId}/set-default`, {
                method: 'POST'
            });
            
            const result = await response.json();
            
            if (!result.success) {
                throw new Error(result.error || '设置默认场景失败');
            }
            
            return true;
        } catch (error) {
            console.error('❌ 设置默认场景失败:', error);
            throw error;
        }
    }

    /**
     * 设置默认项目
     */
    async setDefaultProject(projectId) {
        try {
            const response = await fetch(`${API_BASE_URL}/projects/${projectId}/set-default`, {
                method: 'POST'
            });
            
            const result = await response.json();
            
            if (!result.success) {
                throw new Error(result.error || '设置默认项目失败');
            }
            
            return true;
        } catch (error) {
            console.error('❌ 设置默认项目失败:', error);
            throw error;
        }
    }

    /**
     * 更新场景顺序
     */
    async updateSceneOrder(projectId, sceneIds) {
        try {
            const response = await fetch(`${API_BASE_URL}/projects/${projectId}/scenes/order`, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ sceneIds })
            });
            
            const result = await response.json();
            
            if (!result.success) {
                throw new Error(result.error || '更新场景顺序失败');
            }
            
            return true;
        } catch (error) {
            console.error('❌ 更新场景顺序失败:', error);
            throw error;
        }
    }
}

// 导出单例
const projectAPI = new ProjectAPI();
export default projectAPI;

